package com.green.web.controller.common;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.green.common.page.Pagination;
import com.green.service.common.GetValueService;

@Controller
public class GetValueController extends BaseController{
	
	private static final Logger LOGGER=Logger.getLogger(GetValueController.class);
    @Resource
    private GetValueService getValueService;
    
	@RequestMapping(value="f7/index/{id}")
	public String getValuePage(ModelMap modelMap,@PathVariable String id){
		modelMap.put("sqlId", id);
		modelMap.put("params", mapCopyList(getRequest()));
		if(id.equals("getResource")||id.equals("getOrg")||id.equals("getPosition")){
			modelMap.put("userSize", 100);
		}
		return "common/GetValue";
	}
	@SuppressWarnings("rawtypes")
	@RequestMapping(value="f7/get/{id}")
	@ResponseBody
	public Map<String, Object> getValueList(@PathVariable String id){
		Map<String,Object>  ret=new HashMap<String,Object> ();
		int perPage= getInt("perPage", 1);		
		int pagerNumber=getInt("pagerNumber",10);
		String sqlParams=getString("sqlParams");
		
		String orderByParams=getString("orderBy");
		String sqlId=getString("sqlId");
		try {
			Pagination pagination=new Pagination();
			if(StringUtils.isEmpty(sqlId)){
				pagination= getValueService.getVlaueList(id, new Pagination<HashMap>(perPage,pagerNumber), sqlParams,orderByParams);
			}else{
				pagination= getValueService.getValueListBySqlId(sqlId, new Pagination<Object>(perPage,pagerNumber),sqlParams);
			}
			ret.put("ret", 0);
			ret.put("data",pagination.getItems());
			ret.put("totalRecord", pagination.getRecordCount());
		} catch (Exception e) {
			LOGGER.error(e);
			ret.put("ret", -2);
			ret.put("msg", "系统错误");
		}		
		return ret;
	}
	   @SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value="kp")
	   @ResponseBody
		public Map<String, Object> getKpDate(ModelMap modelMap){
			Map<String,Object> ret=new HashMap<String,Object> ();
			Map<String, Object> params=mapCopyMap(getRequest());		
			String sqlId=getString("sqlId");
			List resultList = getValueService.getValueByKey(sqlId,params);
			ret.put("resultList", resultList);
			ret.put("params", params);
			return ret;
		}
	/***
     * 
     */
    @SuppressWarnings("rawtypes")
	public static Map mapCopyMap(HttpServletRequest request){
    	 Map paraMap=request.getParameterMap();
         Map<String,Object> map=new TreeMap<String,Object>();       
         for (Iterator iter =paraMap.keySet().iterator(); iter.hasNext();)
         {
             String element = ( String ) iter.next();
             String[] txts=( String[] ) paraMap.get(element);
             map.put(element, txts==null?"":txts[0]);
          }        
         return map;    
    }
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static List<Map> mapCopyList(HttpServletRequest request){
        Map paraMap=request.getParameterMap();
        List<Map> list=new ArrayList<Map>();    
        for (Iterator iter =paraMap.keySet().iterator(); iter.hasNext();)
        {
            String element = ( String ) iter.next();
            String[] txts=( String[] ) paraMap.get(element);      
            Map param=new HashMap();
            param.put("key", element);
            String value=txts==null?"":txts[0];
            Pattern pattern=Pattern.compile("(\\w{2})~~(.*)");
            Matcher matcher=pattern.matcher(value);
            if(matcher.find()){
            	String opType=matcher.group(1);
            	value=matcher.group(2);            	
            	param.put("op", SqlTypeEnum.valueOf(opType).getOp());
            }
            param.put("value",value);
            list.add(param);
         } 
        return list;    
    }
    
 
}
